﻿using System;
using System.Configuration;
using System.Data;
using System.IO;
using BLL;
using DAL;
using Ext.Net;
using Roles;

namespace ERP.Modules
{
    public partial class Manufacturer : System.Web.UI.UserControl
    {
        #region[Define]
        private readonly string pathFolderRoot = ConfigurationManager.AppSettings["FolderRoot"];
        private static bool _flag;
        private readonly BllEmployee _clsAutoID = new BllEmployee();
        private readonly BllManufacturer _clsManufacturer = new BllManufacturer();
        private readonly Bank_BLL _clsBank = new Bank_BLL();
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetManufacturer();
                GetBank();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
            }
        }
        //Store
        protected void StoreManufacturer_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            GetManufacturer();
        }
        //Button
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            ClearText();
            GetAutoID();
            _flag = true;
            WindowsManufacturer.Show();
            txtManufacturer_Name.Focus(false, 100);
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grManufacturer.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    _flag = false;
                    ClearText();
                    GetManufacturerEdit(int.Parse(row.RecordID));
                    WindowsManufacturer.Show();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grManufacturer.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    try
                    {
                        var obj = new EtManufacturer { ID_Manufacturer = int.Parse(row.RecordID) };
                        if (obj.Msg == 0)
                            HTML.clsFormat.Alert_ERROR("Thông Báo",
                                "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                        else
                            BllManufacturer.Delete(obj);

                    }
                    catch (Exception ex)
                    {
                        HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
                    }
                }
            GetManufacturer();
        }
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            Insert();
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsManufacturer.Close();
        }
        protected void linkManufacturer_Click(object sender, DirectEventArgs e)
        {
            GetAutoID();
        }
        //Search
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            var dtSearch = _clsManufacturer.GetManufacturer(txtSearch.Text);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                StoreManufacturer.DataSource = dtSearch;
                StoreManufacturer.DataBind();
            }
            else
            {
                grManufacturer.GetStore().RemoveAll();
            }
        }
        //Double-Click
        protected void ManufacturerDblClick(object sender, DirectEventArgs e)
        {
            _flag = false;
            ClearText();
            int ID_Manufacturer = int.Parse(e.ExtraParams["ID_Manufacturer"]);
            GetManufacturerEdit(ID_Manufacturer);
            WindowsManufacturer.Show();
        }
        //FileUpload
        protected void btnUpload_Click(object sender, DirectEventArgs e)
        {
            if (String.IsNullOrEmpty(FileUploadPanel.FileName))
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", "Không có tập tin được chọn !");
            }
            else
            {
                if (CheckFileNameExists("Logo" + "/"))
                {
                    HTML.clsFormat.Alert_ERROR("Lỗi",
                        "Tên tập tin này đã tồn tại trong thư mục " + "Logo" +
                        " vui lòng đổi tên tập tin trước khi tải lên !");
                }
                else
                {
                    Upload(Server.MapPath(pathFolderRoot + "Logo" + "/"));
                }
            }
        }
        protected void btnCancel_Click(object sender, DirectEventArgs e)
        {
            FileUploadPanel.Text = string.Empty;
            WindowFileUploadManufacturer.Close();
        }
        #endregion

        #region[Method]
        private void GetManufacturer()
        {
            var _dtGetManufacturer = _clsManufacturer.GetManufacturer(txtSearch.Text);
            if (_dtGetManufacturer != null && _dtGetManufacturer.Rows.Count > 0)
            {
                StoreManufacturer.DataSource = _dtGetManufacturer;
                StoreManufacturer.DataBind();
            }
            else
            {
                grManufacturer.GetStore().RemoveAll();
            }
        }
        private void GetManufacturerEdit(int id)
        {
            var _dtGetManufacturerEdit = _clsManufacturer.GetManufacturerEdit(id);
            if (_dtGetManufacturerEdit != null && _dtGetManufacturerEdit.Rows.Count > 0)
            {
                hdIDManufacturer.Text = _dtGetManufacturerEdit.Rows[0]["ID_Manufacturer"].ToString();
                txtManufacturer_Alias.Text = _dtGetManufacturerEdit.Rows[0]["Manufacturer_Alias"].ToString();
                txtManufacturer_Name.Text = _dtGetManufacturerEdit.Rows[0]["Manufacturer_Name"].ToString();
                txtLogo.Text = _dtGetManufacturerEdit.Rows[0]["Manufacturer_Logo"].ToString();
                txtEmail.Text = _dtGetManufacturerEdit.Rows[0]["Manufacturer_Email"].ToString();
                txtPhone.Text = _dtGetManufacturerEdit.Rows[0]["Manufacturer_Phone"].ToString();
                txtFax.Text = _dtGetManufacturerEdit.Rows[0]["Manufacturer_Fax"].ToString();
                txtWebsite.Text = _dtGetManufacturerEdit.Rows[0]["Manufacturer_Website"].ToString();
                txtAccountNumber.Text = _dtGetManufacturerEdit.Rows[0]["Account_Number"].ToString();
                if (String.IsNullOrEmpty(_dtGetManufacturerEdit.Rows[0]["Bank_ID"].ToString()))
                {
                    SelectBoxBankManufacturer.Text = string.Empty;
                }
                else
                {
                    SelectBoxBankManufacturer.SelectedItem.Value = _dtGetManufacturerEdit.Rows[0]["Bank_ID"].ToString();
                }
                txtTaxCode.Text = _dtGetManufacturerEdit.Rows[0]["Manufacturer_TaxCode"].ToString();
                txtDateCreate.Text = _dtGetManufacturerEdit.Rows[0]["DateCreate"].ToString();
                txtAddress.Text = _dtGetManufacturerEdit.Rows[0]["Manufacturer_Adress"].ToString();
                txtDescription.Text = _dtGetManufacturerEdit.Rows[0]["Note"].ToString();
            }
        }
        private void GetBank()
        {
            var _dtBank = _clsBank.BindGirdtb_Bank(string.Empty);
            if (_dtBank != null && _dtBank.Rows.Count > 0)
            {
                StoreBankManufacturer.DataSource = _dtBank;
                StoreBankManufacturer.DataBind();
            }
            else
            {
                SelectBoxBankManufacturer.GetStore().RemoveAll();
            }
        }
        private bool CheckInsert()
        {
            var check = false;
            var _clsManufacturerCheck = new BllManufacturer();
            var dtCheck = _clsManufacturerCheck.GetManufacturer(string.Empty);
            if (dtCheck != null && dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheck.Rows)
                {
                    if (hdIDManufacturer.Text != dr["ID_Manufacturer"].ToString())
                    {
                        if (txtManufacturer_Alias.Text == dr["Manufacturer_Alias"].ToString())
                        {
                            check = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã hãng SX " + txtManufacturer_Alias.Text + " đã tồn tại !");
                        }
                        else if (txtManufacturer_Name.Text == dr["Manufacturer_Name"].ToString())
                        {
                            check = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Tên hãng SX " + txtManufacturer_Name.Text + " đã tồn tại !");
                        }
                    }
                }
            }
            return check;
        }
        private void Insert()
        {
            if (_flag)
            {
                InsertValue();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateValue();
                }
            }
        }
        private void InsertValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new EtManufacturer
                    {
                        Manufacturer_Alias = txtManufacturer_Alias.Text,
                        Manufacturer_Name = txtManufacturer_Name.Text,
                        Manufacturer_Logo =txtLogo.Text,
                        Manufacturer_Email = txtEmail.Text,
                        Manufacturer_Phone = txtPhone.Text,
                        Manufacturer_Fax = txtFax.Text,
                        Manufacturer_TaxCode = txtTaxCode.Text,
                        Manufacturer_Website = txtWebsite.Text,
                        Account_Number = txtAccountNumber.Text,
                        Manufacturer_Adress = txtAddress.Text,
                        Note = txtDescription.Text,
                        DateCreate = txtDateCreate.Text == string.Empty ? "NULL" : txtDateCreate.Text,
                        Bank_ID =
                            String.IsNullOrEmpty(SelectBoxBankManufacturer.Text)
                                ? (int?) null
                                : int.Parse(SelectBoxBankManufacturer.SelectedItem.Value),
                    };
                    BllManufacturer.Insert(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công hãng SX");
                    GetManufacturer();
                    ClearText();
                    GetAutoID();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new EtManufacturer
                    {
                        ID_Manufacturer = int.Parse(hdIDManufacturer.Text),
                        Manufacturer_Alias = txtManufacturer_Alias.Text,
                        Manufacturer_Name = txtManufacturer_Name.Text,
                        Manufacturer_Logo = txtLogo.Text,
                        Manufacturer_Email = txtEmail.Text,
                        Manufacturer_Phone = txtPhone.Text,
                        Manufacturer_Fax = txtFax.Text,
                        Manufacturer_TaxCode = txtTaxCode.Text,
                        Manufacturer_Website = txtWebsite.Text,
                        Account_Number = txtAccountNumber.Text,
                        Manufacturer_Adress = txtAddress.Text,
                        Note = txtDescription.Text,
                        DateCreate = txtDateCreate.Text == string.Empty ? "NULL" : txtDateCreate.Text,
                        Bank_ID =
                            String.IsNullOrEmpty(SelectBoxBankManufacturer.Text)
                                ? (int?) null
                                : int.Parse(SelectBoxBankManufacturer.SelectedItem.Value),
                    };
                    BllManufacturer.Update(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật thành công hãng SX");
                    WindowsManufacturer.Close();
                    GetManufacturer();
                    GetAutoID();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void GetAutoID()
        {
            var _dtGetAutoID = _clsAutoID.GetAutoID("Manufacturer_Alias", "tb_Manufacturer");
            if (_dtGetAutoID != null && _dtGetAutoID.Rows.Count > 0)
            {
                try
                {
                    txtManufacturer_Alias.Text = "NCC-0000" +
                                      Convert.ToString(int.Parse(_dtGetAutoID.Rows[0]["Auto_ID"].ToString()) +
                                                       int.Parse(1.ToString()));
                }
                catch (Exception ex)
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", ex.Message);
                }
            }
        }
        protected void ReloadSelectBox(object sender, StoreReadDataEventArgs e)
        {
            GetBank();
        }
        #endregion

        #region[Clear-Text]
        private void ClearText()
        {
            hdIDManufacturer.Text = string.Empty;
            txtManufacturer_Alias.Text = string.Empty;
            txtManufacturer_Name.Text = string.Empty;
            txtDateCreate.Text = string.Empty;
            txtLogo.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtFax.Text = string.Empty;
            txtTaxCode.Text = string.Empty;
            txtWebsite.Text = string.Empty;
            SelectBoxBankManufacturer.Text = string.Empty;
            txtAccountNumber.Text = string.Empty;
            txtDateCreate.Text = string.Empty;
            txtAddress.Text = string.Empty;
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Manufacturer, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelManufacturerMain.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Manufacturer, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion

        #region[Upload]
        private void Upload(string path)
        {
            try
            {
                string tpl;
                tpl = "Tập tin đã tải lên : {0} <br/>Dung lượng : {1} bytes";
                if (FileUploadPanel.HasFile)
                {
                    if (CheckFileType())
                    {
                        FileUploadPanel.PostedFile.SaveAs(path + FileUploadPanel.FileName);
                        X.Msg.Show(new MessageBoxConfig
                        {
                            Buttons = MessageBox.Button.OK,
                            Icon = MessageBox.Icon.INFO,
                            Title = "Thông báo",
                            Message =
                                string.Format(tpl, FileUploadPanel.PostedFile.FileName,
                                    FileUploadPanel.PostedFile.ContentLength)
                        });
                        txtLogo.Text = pathFolderRoot + "Logo/" + FileUploadPanel.FileName;
                        WindowFileUploadManufacturer.Close();
                    }
                    else
                    {
                        X.Msg.Show(new MessageBoxConfig
                        {
                            Buttons = MessageBox.Button.OK,
                            Icon = MessageBox.Icon.ERROR,
                            Title = "Lỗi",
                            Message = "Tập tin " + FileUploadPanel.FileName.Split('.')[1] + " không được hỗ trợ !"
                        });
                    }
                }
                else
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.ERROR,
                        Title = "Lỗi",
                        Message = "Không có tập tin được chọn"
                    });
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private bool CheckFileType()
        {
            var check = FileUploadPanel.PostedFile.FileName.EndsWith(".jpg") ||
                        FileUploadPanel.PostedFile.FileName.EndsWith(".png") ||
                        FileUploadPanel.PostedFile.FileName.EndsWith(".gif");
            return check;
        }
        private bool CheckFileNameExists(string File)
        {
            var check = false;
            var pathUrl = Server.MapPath(pathFolderRoot + File + "/");
            var files = Directory.GetFiles(pathUrl);
            foreach (var fileName in files)
            {
                var fi = new FileInfo(fileName);
                if (fi.Name == FileUploadPanel.FileName)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion

        protected void btnViewImg_Click(object sender, DirectEventArgs e)
        {
            if (String.IsNullOrEmpty(txtLogo.Text))
            {
                 HTML.clsFormat.Alert_ERROR("Lỗi", "Không có ảnh để xem !");
            }
            else
            {
                ImageLogo.ImageUrl = txtLogo.Text;
                WindowViewImages.Show();
            }
        }
    }
}